"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '28/05/2024'
    comment: 商户版
"""
from datetime import datetime
from fastapi import APIRouter, Request, Body, responses

from config import Config
from project.lib.decorator import api_common, exec_duration
from project.lib.common import get_redis
from project.core.function import json_response
from project.model.basic import User
from project.service.agents.agent import Agent
from project.service.agents.merchant import user_role, MerchantService, knowledge_global

merchant_router = APIRouter(prefix='', tags=['商户版'])


@merchant_router.post('/merchant/rich_text/add', summary='富文本信息')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def add_rich_text_add(request: Request,
                            dev_id: str = Body(..., title='设备id'),
                            rich_text: str = Body('', title='富文本信息')):
    """
    **desc**: 添加富文本信息

    **url**: http(s)://{0}.udicaria.com/merchant/rich_text/add

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            rich_text: 富文本信息

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    rds = get_redis()
    key = f'rick_text_{dev_id}'
    rds.set(key, rich_text)
    knowledge_global[dev_id] = ''

    return json_response()


@merchant_router.post('/merchant/rich_text/url', summary='富文本连接')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def get_rich_text_url(request: Request,
                            dev_id: str = Body(..., title='设备id'),
                            user_message: str = Body('', title='用户话术')):
    """
    **desc**: 得到富文本连接

    **url**: http(s)://{0}.udicaria.com/merchant/rich_text/url

    **method**: POST

    **params**:

        <body>:
            dev_id:
            rich_text: 富文本信息

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    url = await MerchantService.get_rich_text_url(dev_id, user_message)

    return json_response(data={'url': url})


@merchant_router.post('/merchant/user/chat/streaming', summary='用户聊天')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_merchant_chat_streaming(request: Request,
                                     dev_id: str = Body(..., title='设备id'),
                                     user_message: str = Body('', title='用户话术')):
    """
    **desc**: 得到富文本连接

    **url**: http(s)://{0}.udicaria.com/merchant/user/chat/streaming

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    response_stream = await MerchantService.chat_streaming(dev_id, user_message)

    return responses.StreamingResponse(response_stream)

@merchant_router.post('/merchant/user/memories/init', summary='清空记忆')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def init_user_memories(request: Request, dev_id: str = Body(..., title='设备id', embed=True)):
    """
    **desc**: 清空用户记忆

    **url**: http(s)://{0}.udicaria.com/hr/user/memories/init

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    agent = Agent(user, user_message='', memories_key='merchant')
    agent.init_user_memories()

    return json_response()

@merchant_router.post('/merchant/user/memories/add', summary='添加聊天记忆')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def add_user_memories(request: Request,
                            dev_id: str = Body(..., title='设备id'),
                            user_message: str = Body('', title='用户话术'),
                            agent_message:  str = Body('', title='agent话术'),):
    """
    **desc**: 添加用户记忆

    **url**: http(s)://{0}.udicaria.com/merchant/user/memories/add

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    now_str = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
    user = User(dev_id=dev_id)
    agent = Agent(user, user_message='', memories_key='merchant')
    if user_message:
        agent.add_user_memories(now_str + f" {user_role}向你说: " + user_message)
    if agent_message:
        agent.add_user_memories(now_str + f" 你向{user_role}说: " + agent_message)

    return json_response()

